﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.NCRD.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.NCRD
{
    public class NCRDService : BPMReportPlatformAppService, INCRDService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;

        public NCRDService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        public async Task<PagedResultDto<GetNCRDOutput>> GetAllAsync(GetNCRDInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetNCRDOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetNCRDOutput>> ExportAsync(GetNCRDInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetNCRDOutput> GetQueryable(GetNCRDInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<NCRDCommissionedAnalysisProcessHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                )
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Address), x => x.Address.Contains(input.Address))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AnalystsUserName),
                    x => x.AnalystsUserName.Contains(input.AnalystsUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CostCenter), x => x.CostCenter.Contains(input.CostCenter))
                .WhereIF(!string.IsNullOrWhiteSpace(input.DelegatorEmail),
                    x => x.DelegatorEmail.Contains(input.DelegatorEmail))
                .WhereIF(!string.IsNullOrWhiteSpace(input.DelegatorUserName),
                    x => x.DelegatorUserName.Contains(input.DelegatorUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InternalNumber),
                    x => x.InternalNumber.Contains(input.InternalNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.PhoneNumber), x => x.PhoneNumber.Contains(input.PhoneNumber))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) => new GetNCRDOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    ProcessStartTime = x.AddTime,
                    ProcessStartUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    Address = x.Address,
                    AnalystsUserName = x.AnalystsUserName,
                    InternalNumber = x.InternalNumber,
                    CostCenter = x.CostCenter,
                    DelegatorUserName = x.DelegatorUserName,
                    PhoneNumber = x.PhoneNumber,
                    DelegatorEmail = x.DelegatorEmail,
                    AnalysisCost = x.AnalysisCost,
                    DiscountAnalysisCost = x.DiscountAnalysisCost,
                    BackgroundPurpose = x.BackgroundPurpose,
                    CcUsersName = x.CcUsersName,
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            // var sql = listQueryable.ToSql().Key;
            return listQueryable;
        }
    }
}